//
//  BCProjectBuyController.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2018/12/6.
//  Copyright © 2018 guoshikeji. All rights reserved.
//

#import "BCProjectBuyController.h"

#import "BCProjectDetailResponse.h"

#import "DDCustomNumberInputView.h"

#import "BCProjectPayPassController.h"

#import "BCWalletPassSetController.h"

#import "BCProjectDetailResponse.h"

//
#import "BCProtocolController.h"

//
#import "BCUserSafeCenterRequest.h"//请求是否设置了支付密码

static NSString *buyProtoclLinkString = @"protocol://";

@interface BCProjectBuyController () <QMUITextViewDelegate,BCWalletPassSetControllerDelegate>

#pragma mark - view
@property (nonatomic, strong) UIView *backgroundView;
@property (nonatomic, strong) UIView *contentView;

/**
 *projectNameLabel
 */
@property (nonatomic, strong) QMUILabel *projectNameLabel;
/**
 *amountTF
 */
@property (nonatomic, strong) QMUITextField *amountTF;
/**
 *customInputView
 */
@property (nonatomic, strong) DDCustomNumberInputView *customInputView;
/**
 *amountCaptionLabel
 */
@property (nonatomic, strong) QMUILabel *amountCaptionLabel;

/**
 *payBalanceLabel
 */
@property (nonatomic, strong) QMUILabel *payBalanceLabel;

/**
 *doneButton
 */
@property (nonatomic, strong) QMUIButton *doneButton;

/**
 *protocolTV
 */
@property (nonatomic, strong) QMUITextView *protocolTV;

/**
 *warningLabel
 */
@property (nonatomic, strong) QMUILabel *warningLabel;


#pragma mark - data
@property (nonatomic, strong) BCProjectDetailData *buyData;

/**
 *preBuy 是否预购
 */
@property (nonatomic, assign) BOOL preBuy;

/**
 *ProjectBuyControllerCompleteBlock
 */
@property (nonatomic, copy) ProjectBuyControllerCompleteBlock completeBlock;

/**
 *contentView动态计算后的高度
 */
@property (nonatomic, assign) CGFloat contentHeight;

@end

@implementation BCProjectBuyController

+ (void)showBuyWithData:(BCProjectDetailData *)detailData preBuy:(BOOL)preBuy complete:(ProjectBuyControllerCompleteBlock)completeBlock {
    BControllerWindow *window = [[BControllerWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
//    window.windowLevel = UIWindowLevelAlert;
    //vc
    BCProjectBuyController *vc = [BCProjectBuyController new];
    vc.showWindow = window;
    vc.buyData = detailData;
    vc.preBuy = preBuy;
    vc.completeBlock = completeBlock;
    BCWindowNavigationController *nav = [[BCWindowNavigationController alloc] initWithRootViewController:vc];
    nav.navigationBar.hidden = true;
    nav.navigationBar.barStyle = UIBarStyleBlack;
    window.rootViewController = nav;
    [window makeKeyAndVisible];
}

- (DDCustomNumberInputView *)customInputView {
    if (!_customInputView) {
        _customInputView = [[DDCustomNumberInputView alloc] initWithFrame:[DDCustomNumberInputView defaultBounds]];
    }
    return _customInputView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    //
    [self setupSubviews];
    //
    [self showContentView];
    //
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldTextDidChangeNotification:) name:UITextFieldTextDidChangeNotification object:self.amountTF];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //
//    self.showWindow.windowLevel = UIWindowLevelAlert;
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    //
//    self.showWindow.windowLevel = UIWindowLevelNormal;
}

- (void)setupSubviews {
    self.backgroundView = [UIView new];
    self.backgroundView.backgroundColor = [UIColor blackColor];
    self.backgroundView.alpha = 0.3;
    [self.view addSubview:self.backgroundView];
    [self.backgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    //
    self.contentView = [UIView new];
    self.contentView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.contentView];
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.width.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.view);
//        make.height.mas_equalTo(ScreenHeight);
    }];
    //
    self.contentView.layer.shadowOpacity = 1;
    self.contentView.layer.shadowRadius = 10.0;
    self.contentView.layer.shadowColor = [UIColor qmui_colorWithHexString:@"#33000000"].CGColor;
    self.contentView.layer.shadowOffset = CGSizeMake(0, -2);
    //
    [self setupContents];
    [self.view layoutIfNeeded];
}
- (void)setupContents {
    //各种间隔的总和
    CGFloat totlePaddingHeight = 0;
    CGFloat leftPadding = 20.0;
    //项目名称
    CGFloat topPadding = 18.0;
    self.projectNameLabel = [QMUILabel new];
    self.projectNameLabel.textColor = [UIColor qmui_colorWithHexString:@"#FF666666"];
    self.projectNameLabel.numberOfLines = 0;
    self.projectNameLabel.font = [UIFont systemFontOfSize:18 weight:UIFontWeightMedium];
    [self.contentView addSubview:self.projectNameLabel];
    [self.projectNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.contentView).offset(topPadding);
        make.left.mas_equalTo(self.contentView).offset(leftPadding);
        make.right.mas_equalTo(self.contentView).offset(-leftPadding);
    }];
    self.projectNameLabel.text = self.buyData.data.project_name;
    [self.projectNameLabel sizeToFit];
    totlePaddingHeight += topPadding;
    //tf
    self.amountTF = [QMUITextField new];
    self.amountTF.textColor = [UIColor qmui_colorWithHexString:@"#FF666666"];
    self.amountTF.tintColor = self.amountTF.textColor;
    self.amountTF.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    self.amountTF.placeholderColor = [UIColor qmui_colorWithHexString:@"#FFD6D6D6"];
    [self.contentView addSubview:self.amountTF];
    [self.amountTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.projectNameLabel.mas_bottom).offset(topPadding);
        make.left.mas_equalTo(self.contentView).offset(leftPadding);
        make.right.mas_equalTo(self.contentView).offset(-leftPadding);
        make.height.mas_equalTo(50.0);
    }];
    self.amountTF.placeholder = self.buyData.flow.buy_placeholder;
    self.amountTF.textInsets = UIEdgeInsetsMake(0, 10, 0, 10);
    self.amountTF.layer.borderColor = [UIColor qmui_colorWithHexString:@"#FFC2C2C2"].CGColor;
    self.amountTF.layer.cornerRadius = 2;
    self.amountTF.layer.borderWidth = 2;
    self.customInputView.textField = self.amountTF;
    totlePaddingHeight += topPadding;
    //caption
    CGFloat captionPadding = 8.0;
    self.amountCaptionLabel = [QMUILabel new];
    self.amountCaptionLabel.textColor = [UIColor qmui_colorWithHexString:@"#FF666666"];
    self.amountCaptionLabel.font = [UIFont systemFontOfSize:11 weight:UIFontWeightRegular];
    self.amountCaptionLabel.numberOfLines = 0;
    [self.contentView addSubview:self.amountCaptionLabel];
    [self.amountCaptionLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.amountTF.mas_bottom).offset(captionPadding);
        make.left.mas_equalTo(self.contentView).offset(leftPadding);
        make.right.mas_equalTo(self.contentView).offset(-leftPadding);
    }];
    self.amountCaptionLabel.text = self.buyData.flow.buy_prompt;
    [self.amountCaptionLabel sizeToFit];
    totlePaddingHeight += captionPadding;
    //pay_balance
    CGFloat payBlancePadding = 40.0;
    self.payBalanceLabel = [QMUILabel new];
    self.payBalanceLabel.textColor = [UIColor qmui_colorWithHexString:@"#FF666666"];
    self.payBalanceLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightRegular];
    [self.contentView addSubview:self.payBalanceLabel];
    [self.payBalanceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.amountCaptionLabel.mas_bottom).offset(payBlancePadding);
        make.left.mas_equalTo(self.contentView).offset(leftPadding);
        make.right.mas_equalTo(self.contentView).offset(-leftPadding);
    }];
    self.payBalanceLabel.text = self.buyData.flow.pay_balance;
    totlePaddingHeight += payBlancePadding;
    //doneButton
    CGFloat doneButtonPadding = 15.0;
    self.doneButton = [QMUIButton new];
    [self.doneButton setTitle:self.buyData.flow.buy_submit forState:UIControlStateNormal];
    [self.doneButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.doneButton.titleLabel.font = [UIFont systemFontOfSize:18 weight:UIFontWeightMedium];
    self.doneButton.backgroundColor = [UIColor darkMainColor];
    self.doneButton.layer.cornerRadius = 2;
    [self.contentView addSubview:self.doneButton];
    [self.doneButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.payBalanceLabel.mas_bottom).offset(doneButtonPadding);
        make.left.mas_equalTo(self.contentView).offset(leftPadding);
        make.right.mas_equalTo(self.contentView).offset(-leftPadding);
        make.height.mas_equalTo(50.0);
    }];
    [self.doneButton addTarget:self action:@selector(doneButtonDidClickedAction) forControlEvents:UIControlEventTouchUpInside];
    totlePaddingHeight += doneButtonPadding;
    //比较麻烦的底部tv
    CGFloat protocolTVPadding = 11.0;
    self.protocolTV = [QMUITextView new];
    self.protocolTV.textAlignment = NSTextAlignmentCenter;
    self.protocolTV.scrollEnabled = false;
    self.protocolTV.editable = false;
    self.protocolTV.delegate = self;
    self.protocolTV.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0);
    [self.contentView addSubview:self.protocolTV];
    [self.protocolTV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.doneButton.mas_bottom).offset(protocolTVPadding);
        make.left.mas_equalTo(self.contentView).offset(leftPadding);
        make.right.mas_equalTo(self.contentView).offset(-leftPadding);
//        make.height.mas_equalTo(40.0);
    }];
    self.protocolTV.linkTextAttributes = @{ NSForegroundColorAttributeName: [UIColor qmui_colorWithHexString:@"#FFAEAEAE"],
                                            NSUnderlineColorAttributeName: [UIColor qmui_colorWithHexString:@"#FFAEAEAE"],
                                            NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)};

    NSMutableParagraphStyle *protocolPs = [[NSMutableParagraphStyle alloc] init];
    protocolPs.alignment = NSTextAlignmentCenter;
    NSString *protocolString = [NSString stringWithFormat:@"%@%@",self.buyData.flow.risk_warning.text,self.buyData.flow.risk_warning.agreement];
    NSMutableAttributedString *protocolAttri = [[NSMutableAttributedString alloc] initWithString:protocolString attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13 weight:UIFontWeightRegular],NSForegroundColorAttributeName:[UIColor qmui_colorWithHexString:@"#FFAEAEAE"],NSParagraphStyleAttributeName:protocolPs}];
    
    NSRange linkRange = [protocolString rangeOfString:self.buyData.flow.risk_warning.agreement];
    if (linkRange.location!=NSNotFound) {
        [protocolAttri addAttribute:NSLinkAttributeName value:buyProtoclLinkString range:linkRange];
    }
    
    self.protocolTV.attributedText = protocolAttri;
    totlePaddingHeight += protocolTVPadding;
    [self.protocolTV sizeToFit];
    //
    CGFloat warningPadding = 3.0;
    self.warningLabel = [QMUILabel new];
    self.warningLabel.textAlignment = NSTextAlignmentCenter;
    self.warningLabel.textColor = [UIColor qmui_colorWithHexString:@"#FFAEAEAE"];
    self.warningLabel.numberOfLines = 0;
    self.warningLabel.font = [UIFont systemFontOfSize:12 weight:UIFontWeightRegular];
    [self.contentView addSubview:self.warningLabel];
    [self.warningLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.protocolTV.mas_bottom).offset(warningPadding);
        make.left.mas_equalTo(self.contentView).offset(leftPadding);
        make.right.mas_equalTo(self.contentView).offset(-leftPadding);
    }];
    self.warningLabel.text = self.buyData.flow.warning;
    [self.warningLabel sizeToFit];
    totlePaddingHeight += warningPadding;
    //
    CGFloat bottomPadding = 15.0;
    totlePaddingHeight += bottomPadding;
    [self.contentView layoutIfNeeded];
    //
    CGFloat contentHeight = totlePaddingHeight;
    contentHeight += CGRectGetHeight(self.projectNameLabel.frame);
    contentHeight += CGRectGetHeight(self.amountTF.frame);
    contentHeight += CGRectGetHeight(self.amountCaptionLabel.frame);
    contentHeight += CGRectGetHeight(self.payBalanceLabel.frame);
    contentHeight += CGRectGetHeight(self.doneButton.frame);
    contentHeight += CGRectGetHeight(self.protocolTV.frame);
    contentHeight += CGRectGetHeight(self.warningLabel.frame);
    //
    self.contentHeight = contentHeight+Height_Bottom_SafeArea;
    //
    [self.contentView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(self.contentHeight);
        make.bottom.mas_equalTo(self.view).offset(self.contentHeight);
    }];
}


#pragma mark - action
- (void)showContentView {
    [self.contentView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.view).offset(0);
    }];
    [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        
    }];
}
- (void)dismissContentView {
    [self.contentView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.view).offset(self.contentHeight);
    }];
    [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        [self dismissWindow];
    }];
}

#pragma mark - UITextViewDelegate

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
    if ([URL.absoluteString isEqualToString:buyProtoclLinkString]) {
        [BCProtocolController showFromController:self.navigationController protocolURLString:self.buyData.flow.risk_warning.url];
        return false;
    }
    return YES;
}

#pragma mark - doneButtonDidClickedAction
- (void)doneButtonDidClickedAction {
    if (!self.amountTF.text.length) {
        [self.amountTF becomeFirstResponder];
        return;
    }
    NSString *amount = self.amountTF.text;
    CGFloat amountValue = amount.floatValue;
    if (amountValue<=0) {
        [self.amountTF becomeFirstResponder];
        return;
    }
    //
    CGFloat minBuy = self.buyData.data.min_buy.floatValue;
    CGFloat maxBuy = self.buyData.data.max_buy.floatValue;
    if (amountValue<minBuy || amountValue>maxBuy) {
        //eg:BTC
        NSString *curr = self.buyData.data.curr;
        //起购范围
        NSString *range = self.buyData.flow.range;
        NSString *alertString = [NSString stringWithFormat:@"%@：%@%@ - %@%@",range,self.buyData.data.min_buy,curr,self.buyData.data.max_buy,curr];
        [QMUITips showInfo:alertString inView:self.showWindow hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:alertString]];
        return;
    }
    //
    [self checkUserSetPayPass];
}


#pragma mark - textFieldTextDidChangeNotification:
- (void)textFieldTextDidChangeNotification:(NSNotification *)noti {
    id object = noti.object;
    if (object) {
        if (object==self.amountTF) {
            NSString *text = self.amountTF.text;
            if (text.length==1&&[text isEqualToString:@"."]) {//第一个输入.时 补0
                self.amountTF.text = @"0.";
            }
            if (text.length>1) {
                //只能输入到小数点后两位
                NSRange pointRange = [text rangeOfString:@"."];
                if (pointRange.location!=NSNotFound) {//有小数点 就不能输入小数点了
                    //判断小数点是不是最后一位
                    NSString *lastChar = [text substringFromIndex:text.length-1];
                    if (pointRange.location==text.length-1&&[lastChar isEqualToString:@"."]) {//说明输入的最后一位是小数点
                        
                    }else if([lastChar isEqualToString:@"."]) {
                        //如果最后一位是小数点 并且已经有了小数点 不能输入
                        text = [text substringToIndex:text.length-1];
                        self.amountTF.text = text;
                    }
                    //小数点后几位
                    NSInteger pointNumber = 8;
                    if (text.length-(pointRange.location+1)>pointNumber) {
                        self.amountTF.text = [text substringToIndex:pointRange.location+pointNumber+1];
                    }
                }else {//没有小数点 位数不能超过100000
                    //                    if (text.length>6) {
                    //                        self.textField.text = [text substringToIndex:6];
                    //                    }
                }
            }
        }
    }
}
//
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    UITouch *touch = touches.anyObject;
    CGPoint touchPoint = [touch locationInView:self.view];
    if (!CGRectContainsPoint(self.contentView.frame, touchPoint)) {
        [self dismissContentView];
    }
}

#pragma mark - toPayAction
- (void)toPayAction:(BCUserSafeCenterData *)safeData {
    //判断是否开启支付密码
    if (safeData.data.has_pay_pass) {
        //弹出支付界面
        [self toInputPayPassAction];
    }else {
        WEAK_SELF
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:safeData.flow.no_paypass.mess message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:safeData.flow.no_paypass.cancel style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *setting = [UIAlertAction actionWithTitle:safeData.flow.no_paypass.sub style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [wself toSetPayPassAction];
        }];
        [alertVC addAction:cancel];
        [alertVC addAction:setting];
        [self presentViewController:alertVC animated:true completion:nil];
    }
}
/**
 弹出支付密码输入界面 并完成支付
 */
- (void)toInputPayPassAction {
    WEAK_SELF
    NSString *subId = [NSString stringWithFormat:@"%@",@(self.buyData.data.sub_id)];
    if (self.preBuy) {
        subId = [NSString stringWithFormat:@"%@",@(self.buyData.data.sub_id)];
    }
    NSString *amount = self.amountTF.text;
    [BCProjectPayPassController showPay:subId amount:amount fromController:self complete:^(NSString *successMsg) {
        if (wself.completeBlock) {
            wself.completeBlock(successMsg);
        }
        [wself dismissContentView];
    }];
}

#pragma mark -
/**
 检查是否设置了支付密码
 */
- (void)checkUserSetPayPass {
    BCUserSafeCenterData *safeData = [BCUserManager sharedUser].safeCenterData;
    if (safeData) {
        //去支付
        [self toPayAction:safeData];
    }else {
        [self requestPayPassSetAction];
    }
}

#pragma mark - other request
- (void)requestPayPassSetAction {
    //请求一次是否设置了支付密码
    WEAK_SELF
    [self.doneButton bc_showActivityIndicatorBackgroundColor:self.doneButton.backgroundColor insets:UIEdgeInsetsZero activityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];
    [BCUserSafeCenterRequest requestData:^(BCUserSafeCenterResponse * _Nonnull resp, NSError * _Nonnull error) {
        [wself.doneButton bc_hiddenActivityIndicator];
        if (error) {
            if (wself.view) {
                NSString *errMsg = error.domain;
                [QMUITips showError:errMsg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:errMsg]];
            }
        }else {
            //去支付
            [wself toPayAction:resp.data];
        }
    }];
}

/**
 去设置支付密码
 */
- (void)toSetPayPassAction {
    //需要处理数据
    BCUserSafeCenterData *data = [BCUserManager sharedUser].safeCenterData;
    NSString *account;
    BCaptchaSendType sendType = BCaptchaSendTypePhone;
    if (data.data.has_email) {
        account = data.data.email;
        sendType = BCaptchaSendTypeEmail;
    }else if (data.data.has_phone) {
        account = data.data.phone;
        sendType = BCaptchaSendTypePhone;
    }
    if (!account.length) {
        return;
    }
    BCWalletPassSetController *pass = [BCWalletPassSetController new];
    pass.account = account;
    pass.sendType = sendType;
    pass.delegate = self;
    [self.navigationController pushViewController:pass animated:true];
}
#pragma mark - BCWalletPassSetControllerDelegate
- (void)walletPassSetSuccessAction {
    [BCUserSafeCenterRequest requestData:^(BCUserSafeCenterResponse * _Nonnull resp, NSError * _Nonnull error) {
        
    }];
}


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:self.amountTF];
}

@end
